#!/bin/bash
# Copyright 2019-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#  * Neither the name of NVIDIA CORPORATION nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

############################################################################
## This script generates custom operations needed by some of the
## Triton's CI tests. Generating these custom operations requires
## using the Pytorch container.
##
## 1. Update PYTORCH_IMAGE to match what is being
## used by the Triton release being tested.
##
## 2. Run this script to create /tmp/qa_custom_ops.
##
############################################################################

TRITON_VERSION=${TRITON_VERSION:=25.04}
NVIDIA_UPSTREAM_VERSION=${NVIDIA_UPSTREAM_VERSION:=$TRITON_VERSION}
PYTORCH_IMAGE=${PYTORCH_IMAGE:=nvcr.io/nvidia/pytorch:$NVIDIA_UPSTREAM_VERSION-py3}
UBUNTU_IMAGE=${UBUNTU_IMAGE:=ubuntu:24.04}

CUDA_DEVICE=${NV_GPU:=0}

DOCKER_GPU_ARGS=${DOCKER_GPU_ARGS:-$([[ $RUNNER_GPUS =~ ^[0-9] ]] && eval $NV_DOCKER_ARGS || echo "--gpus device=$CUDA_DEVICE" )}

############################################################################
# Check if Docker volume exists
############################################################################
CI_JOB_ID=${CI_JOB_ID:=$(date +%Y%m%d_%H%M)}
DOCKER_VOLUME=${DOCKER_VOLUME:=volume.gen_qa_custom_ops.${CI_JOB_ID}}
RUNNER_ID=${RUNNER_ID:=0}
PROJECT_NAME=${PROJECT_NAME:=tritonserver}
DOCKER_VOLUME_CONTAINER=${DOCKER_VOLUME}.gen_qa_custom_ops.${CI_JOB_ID}

if ! docker volume inspect $DOCKER_VOLUME > /dev/null 2>&1; then
    echo -e "\033[34m[ INFO ] - Docker volume $DOCKER_VOLUME does not exist. Creating... \033[0m "
    docker volume create $DOCKER_VOLUME --label RUNNER_ID=$RUNNER_ID --label PROJECT_NAME=$PROJECT_NAME
    docker volume inspect $DOCKER_VOLUME
else
    echo -e "\033[34m[ INFO ] - Docker volume in use: $DOCKER_VOLUME \033[0m "
    docker volume inspect $DOCKER_VOLUME
fi


docker run \
    --rm \
    --label RUNNER_ID=$RUNNER_ID \
    --label PROJECT_NAME=$PROJECT_NAME \
    -v $DOCKER_VOLUME:/mnt \
    -w /mnt/$CI_JOB_ID \
    $UBUNTU_IMAGE \
    mkdir -p gen_srcdir ${TRITON_VERSION}

docker create \
    --label RUNNER_ID=$RUNNER_ID \
    --label PROJECT_NAME=$PROJECT_NAME \
    --name $DOCKER_VOLUME_CONTAINER \
    -v $DOCKER_VOLUME:/mnt \
    -w /mnt/$CI_JOB_ID \
    $UBUNTU_IMAGE

docker cp . $DOCKER_VOLUME_CONTAINER:/mnt/$CI_JOB_ID/gen_srcdir

###
VOLUME_BUILD_DIR=${VOLUME_BUILD_DIR:=/mnt/$CI_JOB_ID}
VOLUME_SRCDIR=${VOLUME_SRCDIR:=$VOLUME_BUILD_DIR/gen_srcdir}
VOLUME_DESTDIR=$VOLUME_BUILD_DIR/$TRITON_VERSION/qa_custom_ops


docker run --rm -v $DOCKER_VOLUME:/mnt -w /mnt/$CI_JOB_ID $UBUNTU_IMAGE \
mkdir -p \
$VOLUME_DESTDIR/libtorch_custom_ops

PYTSCRIPT=gen.PyTorch.gen_qa_custom_ops.cmds

# PyTorch

cat > $PYTSCRIPT <<EOF
#!/bin/bash -x
# Make all generated files accessible outside of container
umask 0000
nvidia-smi --query-gpu=compute_cap,compute_mode,driver_version,name,index --format=csv || true
nvidia-smi || true
set -e
export TORCH_EXTENSIONS_DIR="/root/.cache/torch_extensions/"
python3 $VOLUME_SRCDIR/gen_qa_custom_ops_models.py --libtorch --models_dir=\$DESTDIR
cp \${TORCH_EXTENSIONS_DIR}/custom_modulo/custom_modulo.so \$DESTDIR/libtorch_modulo/.
chmod -R 777 \$DESTDIR
EOF

chmod a+x $PYTSCRIPT
if [ $? -ne 0 ]; then
    echo -e "Failed: chmod"
    exit 1
fi

docker cp $PYTSCRIPT $DOCKER_VOLUME_CONTAINER:$VOLUME_SRCDIR/$PYTSCRIPT

docker pull $PYTORCH_IMAGE

echo -e "\033[34m[ INFO ] - Running:  $PYTSCRIPT \033[0m "

docker run \
    --rm \
    --label RUNNER_ID=$RUNNER_ID \
    --label PROJECT_NAME=$PROJECT_NAME \
    $DOCKER_GPU_ARGS \
    -v $DOCKER_VOLUME:/mnt \
    -e DESTDIR=$VOLUME_DESTDIR/libtorch_custom_ops \
    $PYTORCH_IMAGE \
    bash -xe $VOLUME_SRCDIR/$PYTSCRIPT

if [ $? -ne 0 ]; then
    echo -e "Failed"
    exit 1
fi


if [ -z $CI ] ; then
    echo -e "\033[34m[ INFO ] - Copying generated models to /tmp/ \033[0m "
    docker cp $DOCKER_VOLUME_CONTAINER:$VOLUME_BUILD_DIR/$TRITON_VERSION /tmp/
    echo -e "\033[34m[ INFO ] - Removing Docker container $DOCKER_VOLUME_CONTAINER \033[0m "
    docker rm -f $(docker ps -a --filter volume=$DOCKER_VOLUME --format '{{ .ID }}')
    echo -e "\033[34m[ INFO ] - Removing Docker volume $DOCKER_VOLUME \033[0m "
    docker volume rm $DOCKER_VOLUME
fi